'use strict';

module.exports = app => {
  const { STRING, INTEGER, TEXT, JSON } = app.Sequelize;

  const UserPreference = app.model.define('user_preference', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    user_id: {
      type: INTEGER,
      allowNull: false,
      comment: '用户ID',
    },
    preference_type: {
      type: STRING(50),
      allowNull: false,
      comment: '偏好类型(style, color, occasion, brand等)',
    },
    preference_key: {
      type: STRING(100),
      allowNull: false,
      comment: '偏好键',
    },
    preference_value: {
      type: TEXT,
      allowNull: true,
      comment: '偏好值',
    },
    preference_data: {
      type: JSON,
      allowNull: true,
      comment: '偏好数据(JSON格式)',
    },
    weight: {
      type: INTEGER,
      defaultValue: 1,
      comment: '权重(1-10)',
    },
    description: {
      type: TEXT,
      allowNull: true,
      comment: '描述',
    },
    // 时间戳字段由Sequelize自动管理
  }, {
    tableName: 'user_preferences',
    paranoid: false,  // 禁用软删除
    comment: '用户偏好表',
    indexes: [
      {
        fields: ['user_id'],
      },
      {
        fields: ['preference_type'],
      },
      {
        unique: true,
        fields: ['user_id', 'preference_type', 'preference_key'],
      },
    ],
  });

  UserPreference.associate = function() {
    // 偏好属于用户
    app.model.UserPreference.belongsTo(app.model.User, {
      foreignKey: 'user_id',
      as: 'user',
    });
  };

  return UserPreference;
};
